package ch.kerbtier.webglue;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlueServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response, getServletContext(), getServletConfig());
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doRequest(request, response, getServletContext(), getServletConfig());
	}

	private void doRequest(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext,
			ServletConfig servletConfig) {

		boolean sessionIsNew = request.getSession(false) == null;

		final CodeRunner codeRunner = (CodeRunner) servletContext.getAttribute("glue_code_runner");
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("servletContext", servletContext);
		parameters.put("context", servletContext);
		parameters.put("request", request);
		parameters.put("session", request.getSession());
		parameters.put("newSession", sessionIsNew);
		parameters.put("response", response);
		parameters.put("servletConfig", servletConfig);

		codeRunner.run(servletConfig.getInitParameter("name") + ".groovy", parameters);
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init() throws ServletException {
	}
}
